package com.graduation.check.mapper;

import com.graduation.check.entity.CheckTask;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Mapper
public interface CheckTaskMapper {

    @Insert("INSERT INTO check_task (student_id, paper_title, original_file_name, stored_file_name, file_path, status, upload_time) " +
            "VALUES (#{studentId}, #{paperTitle}, #{originalFileName}, #{storedFileName}, #{filePath}, #{status}, #{uploadTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(CheckTask task);

    @Select("SELECT * FROM check_task WHERE id = #{id}")
    Optional<CheckTask> findById(Long id);

    @Select("SELECT * FROM check_task WHERE student_id = #{studentId} ORDER BY upload_time DESC")
    List<CheckTask> findByStudentId(Long studentId);

    @Select("SELECT ct.*, u.name as student_name FROM check_task ct " +
            "LEFT JOIN user u ON ct.student_id = u.id " +  // 修正表名为 users
            "WHERE u.department = #{department} ORDER BY ct.upload_time DESC")
    List<CheckTask> findByDepartment(String department);

    @Select("SELECT * FROM check_task WHERE paper_title IS NOT NULL AND status = 'COMPLETED'")
    List<CheckTask> findAllCompletedPapers();

    @Select("SELECT * FROM check_task WHERE paper_title IS NOT NULL AND status = 'COMPLETED' AND upload_time >= #{startDate}")
    List<CheckTask> findRecentPapers(@Param("startDate") LocalDateTime startDate);

    @Select("SELECT * FROM check_task WHERE paper_title IS NOT NULL AND status = 'COMPLETED' AND student_id != #{excludeStudentId}")
    List<CheckTask> findOtherStudentsPapers(@Param("excludeStudentId") Long excludeStudentId);

    @Select("SELECT * FROM check_task WHERE paper_title IS NOT NULL AND status = 'COMPLETED' AND upload_time >= #{startDate} AND student_id != #{excludeStudentId}")
    List<CheckTask> findOtherStudentsRecentPapers(@Param("excludeStudentId") Long excludeStudentId,
                                                  @Param("startDate") LocalDateTime startDate);

    @Update("UPDATE check_task SET similarity_rate=#{similarityRate}, check_result=#{checkResult}, status=#{status}, check_time=#{checkTime} WHERE id=#{id}")
    void updateResult(CheckTask task);

    @Update("UPDATE check_task SET teacher_id=#{teacherId}, teacher_comment=#{teacherComment}, passed=#{passed} WHERE id=#{id}")
    void updateReview(CheckTask task);

    @Select("SELECT COUNT(*) FROM check_task WHERE status = #{status}")
    Integer countByStatus(String status);
}